package com.product.android.business.manager;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

import android.text.TextUtils;

import com.common.android.utils.NetWorkUtils;
import com.product.android.business.ApplicationVariable;
import com.product.android.business.login.BindUser;
import com.product.android.utils.LogUtils;
import com.product.android.utils.SharedPreferenceHelper;


public class DataUpdateManager {
	public static final String KEY_BLACKLIST="weibo_blacklist_update";
	public static final String KEY_FOLLOWLIST="weibo_followlist_update";
    public static final String KEY_USERINFO="userinfo_update";
    public static final String KEY_GROUP="group_update";
    public static final String KEY_UNIT="unit_update";
    public static final String KEY_FRIENDLIST="friend_list_update";
    public static final String KEY_HEAD_IMAGE="head_image_update";
    public static final String KEY_SIGN_INONEDAY="sign_in_one_day";
    public static final String KEY_FLOWER_MSG="flower_msg_update";
    public static final String KEY_APP_UPDATE="app_update";
    
    private static final long HOUR_MILLIS=3600000;
	private static DataUpdateManager mInstance;
	private SharedPreferenceHelper mPreferenceHelper;
	private HashMap<String, String> mJsonMap=new HashMap<String, String>();

	public static DataUpdateManager getInstance(){
		if (mInstance==null){
			mInstance=new DataUpdateManager();
		}
		return mInstance;
	}
	
	private DataUpdateManager(){
		mPreferenceHelper=SharedPreferenceHelper.getInstance(ApplicationVariable.INSTANCE.applicationContext);
	}

	public boolean isNeedUpdate(String key){
//		if (!IMSStateManager.getInstance().isNetworkAvailable()){
//			//无网络连接
//			return false;
//		}
		if(!NetWorkUtils.JudgeNetWorkStatus(ApplicationVariable.INSTANCE.applicationContext)){
			//无网络连接
			return false;
		}
		BindUser bindUser = ApplicationVariable.INSTANCE.getIUser().getBindUser();
		if(bindUser == null || bindUser.getUid() == 0) {
			LogUtils.e(LogUtils.M_START,"empty current user(binduser)");
			return false;
		}
		String fullKey=bindUser.getUid()+key;
		long value=mPreferenceHelper.loadLongKey(fullKey,0L);
		if (value==0){
			return true;
		}
		return checkTime(value);
	}
	
	public boolean isNeedUpdate(String key,long fid){
//		if (IMSStateManager.getInstance().isNetworkAvailable()){
//			//无网络连接
////			Log.d("debug", "no net work,no nedd update");
//			return false;
//		}		
		if(!NetWorkUtils.JudgeNetWorkStatus(ApplicationVariable.INSTANCE.applicationContext)){
			//无网络连接
			return false;
		}

		BindUser bindUser = ApplicationVariable.INSTANCE.getIUser().getBindUser();
		if(bindUser == null || bindUser.getUid() == 0) {
			LogUtils.e(LogUtils.M_START,"empty current user(binduser)");
			return false;
		}
		String fullKey=bindUser.getUid()+key;
		String dataJson="";
		if (mJsonMap.containsKey(fullKey)){
			dataJson=mJsonMap.get(fullKey);
		}else{
			dataJson=mPreferenceHelper.loadKey(fullKey);
			mJsonMap.put(fullKey, dataJson);
		}
		if (TextUtils.isEmpty(dataJson)){
			LogUtils.d("debug", "empty json:"+fid);
			return true;
		}
		try {
			JSONObject data=new JSONObject(dataJson);
			if (data.has(""+fid)){
				long value=data.getLong(""+fid);
				if (value==0){
//					Log.d("debug", "get value from json is 0");
					return true;
				}
				return checkTime(value);
			}else{
//				Log.d("debug", dataJson+ " doesn't contain "+fid+",need update");
			}
		} catch (JSONException e) {
			LogUtils.d("debug", "set jsondata error:"+dataJson);
			e.printStackTrace();
		}
		return true;
	}
	
	
	/**
	 * <br>Description:TODO  当前用户状态标志是不是当前
	 * <br>Author:daiyf
	 * <br>Date:2013-10-18上午10:49:54
	 * @param key
	 * @param fid
	 * @return  true 要去请求 ， 否则返回false不请求
	 */
	public boolean isNotInOneDay(String key,long fid){
		String fullKey=fid+key;
		String value="";
		if (mJsonMap.containsKey(fullKey)){
			value=mJsonMap.get(fullKey);
		}else{
			value=mPreferenceHelper.loadKey(fullKey);
			mJsonMap.put(fullKey, value);
		}

		//无记录，未检查过
		if (TextUtils.isEmpty(value)){
			return true;
		}		

		SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd");    
		Date curDate = new Date(System.currentTimeMillis());//获取当前时间       
		String str =  sDateFormat.format(curDate);  
		
		if(value.equalsIgnoreCase(str)){
			return false;
		}
		else{
//			if (IMSStateManager.getInstance().isNetworkAvailable()){
//				//无网络连接
//				return false;
//			}
			if(!NetWorkUtils.JudgeNetWorkStatus(ApplicationVariable.INSTANCE.applicationContext)){
				//无网络连接
				return false;
			}
			return true;
		}
	}
	
	/**
	 * 判断间隔时间是否达到 wifi下1h, 非wifi 24h
	 * 
	 * <br>Created 2014-5-9 上午10:38:15
	 * @param value	 上一次的更新时间戳
	 * @return
	 * @author        :  huangszh
	 */
	private boolean checkTime(long value){
		
		return checkTime(value, 24f, 1f);
	}
	
	/**
	 * 判断间隔时间是否达到
	 * 
	 * <br>Created 2014-5-9 上午10:21:39
	 * @param value		上一次的更新时间戳
	 * @param no_wifi_space		非wifi下间隔时间 单位h
	 * @param wifi_space		wifi下间隔时间	单位h
	 * @return
	 * @author        :  huangszh
	 */
	public boolean checkTime(long value,float no_wifi_space,float wifi_space){
		long now=System.currentTimeMillis();
		float times= wifi_space;
		String tag="WIFI:";
		if(!NetWorkUtils.isWifi()){
			//非WIFI环境
			times= no_wifi_space;
			tag="2G/3G:";			
		}
//		if (NetWorkUtils.getAPNType(ChatConfiguration.mContext)!=NetWorkUtils.WIFI){
//		}
		long timePassed=now-value;
		if (timePassed>=(times*HOUR_MILLIS)){
//			Log.d("debug", tag+"time passed "+timePassed+ "("+((float)timePassed/HOUR_MILLIS)+" hours),need update:"+mTestKey+" ,");
			return true;
		}
//		Log.d("debug", tag+"time passed "+timePassed+ "("+((float)timePassed/HOUR_MILLIS)+" hours),no need update:"+mTestKey+" ,"+mTestFid);
		return false;
	}
	
	public void save(String key,long time){
		String fullKey=ApplicationVariable.INSTANCE.getIUser().getBindUser().getUid()+key;
		mPreferenceHelper.saveLongKey(fullKey, time);
	}
	
	/**
	 * 根据关键字查找查找对应值， 判断使用
	 * <br>Created 2014-5-4 下午5:53:14
	 * @param key 查找关键字
	 * @return  时间戳
	 * @author       Administrator
	*/
	public long getKeyTime(String key){
		String fullKey=ApplicationVariable.INSTANCE.getIUser().getBindUser().getUid()+key;
		return mPreferenceHelper.loadLongKey(fullKey, 0);
	}
	
	public void save(String key,String data){
		String fullKey=ApplicationVariable.INSTANCE.getIUser().getBindUser().getUid()+key;
		mPreferenceHelper.saveKey(fullKey, data);
		mJsonMap.put(fullKey, data);
	}
	
	public void saveJson(String key,long fid){
		String fullKey=ApplicationVariable.INSTANCE.getIUser().getBindUser().getUid()+key;
		String dataJson="";
		JSONObject data=null;
		try {
			if (mJsonMap.containsKey(fullKey)){
				dataJson=mJsonMap.get(fullKey);
			}
			if (!TextUtils.isEmpty(dataJson)){
				data=new JSONObject(dataJson);
			}else{
				data=new JSONObject();	
			}
			data.put(""+fid, System.currentTimeMillis());
			dataJson=data.toString();
			mJsonMap.put(fullKey, dataJson);
			mPreferenceHelper.saveKey(fullKey, dataJson);
//			Log.d("debug", "save json:"+fullKey+","+dataJson);
		} catch (JSONException e) {
			LogUtils.d("debug", "saveJson error");
			e.printStackTrace();
		}
	}
	
	public void clearJson() {
		mJsonMap.clear();
	}
}
